package com.help10000.rms.ui.activitys

import android.content.Intent
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.amir.common.beans.OrderItem
import com.amir.common.utils.CustomToolBar
import com.amir.common.utils.DensityUtil
import com.amir.common.utils.IMEUtil
import com.amir.common.utils.LogUtils
import com.amir.common.utils.PermissionUtils
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.common.PlayerState
import com.help10000.rms.common.VoicePlayer
import com.help10000.rms.mvp.presenter.MyOrderPresenter
import com.help10000.rms.mvp.view.MyOrderView
import com.help10000.rms.ui.adapter.OrderAdapter
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.ui.utils.JsonUtils.TAG
import com.help10000.rms.ui.utils.PageUtils
import com.help10000.rms.ui.windows.SelectOrderStatusPopuWindow
import com.help10000.rms.utils.LocationManager
import kotlinx.android.synthetic.main.activity_my_order.*

/**
 * 我的订单
 */
class OrderActivity() : BaseActivity<MyOrderPresenter, MyOrderView>(), MyOrderView, Parcelable {
    var player = VoicePlayer()
    var page = 1
    var tel: String? = null
    var type = 0//0是我的订单，1是抢单，2是超时,3是服务历史
    var orderAdapter: OrderAdapter? = null
    var list = mutableListOf<OrderItem>()
    override fun getlayoutId(): Int {
        return R.layout.activity_my_order
    }
    private lateinit var titleBar: CustomToolBar
    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("type", type)
        outState.putString("tel", tel)
        super.onSaveInstanceState(outState)
    }



    override fun initView() {
        player.setStateListener(object : VoicePlayer.PlayStateListener {
            override fun onNotify(state: PlayerState) {
                when (state) {
                    PlayerState.PREPARING -> {
                        showLoading()
                    }
                    PlayerState.PLAYING -> {
                        dismissLoading()
                    }
                }
            }
        })
        titleBar = findViewById(R.id.titleBar)
        // 初始化列表布局（提前设置，避免首次加载时为null）
        rv_list.layoutManager = LinearLayoutManager(mContext)
    }


    override fun enableLoadMore(): Boolean {
        return type != 1
    }

    override fun initData(savedInstanceState: Bundle?) {
        if (savedInstanceState == null) {
            type = intent.getIntExtra("type", 0)
            tel = intent.getStringExtra("tel")
        } else {
            type = savedInstanceState.getInt("type")
            tel = savedInstanceState.getString("tel")
        }
        initRefreshLayout(refresh)

        if (type != 0)
            searchOrderLayout.visibility = View.GONE
        loadData()
    }

    fun loadData() {
        when (type) {
            0 -> {
                titleBar.setTitle("我的工单")
                mPresenter.getOrderList(page, activity = this)
            }
            1 -> {
                titleBar.setTitle("抢单")
                page = 1
                mPresenter.getRobOrderList(activity = this)
            }
            2 -> {
                titleBar.setTitle("超时工单")
                mPresenter.getTimeOutOrderList(page)
            }
            3 -> {
                titleBar.setTitle("客户服务历史")
                mPresenter.getServiceHistory(page, tel)
            }
        }
    }

    override fun initListener() {
        super.initListener()
        tv_orderStatus.setOnClickListener(DuplicateClickProxy {
            val popuWindow = SelectOrderStatusPopuWindow(
                mContext, layoutInflater.inflate(R.layout.popu_select_picking, null),
                DensityUtil.dp2px(280f),
                DensityUtil.dp2px(300f)
            )
            popuWindow.showAtLocation(
                tv_orderStatus,
                Gravity.CENTER,
                0,
                0
            )
            popuWindow.mOnResultListener = object : SelectOrderStatusPopuWindow.OnResultListener {
                override fun onResult(status: String, name: String) {
                    mPresenter.status = status
                    tv_orderStatus.text = name
                    page = 1
                    loadData()
                }

            }
        })


//        titleBar.setOnLeftClickListener {
//            // 跳转到工单页面（假设工单页面是MainActivity中的WorkOrderFragment）
//            val intent = Intent(this, MainActivity::class.java).apply {
//                // 传递参数标识需要显示的是“工单”页面
//                putExtra("TARGET_FRAGMENT", "WORK_ORDER") // 与MainActivity约定的标识
//                // 清除栈顶，避免重复创建页面
//                flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
//            }
//            startActivity(intent)
//            finish() // 关闭当前页面
//        }

        btn_search.setOnClickListener(DuplicateClickProxy {
            mPresenter.searchKey = et_searchs.text.toString().trim()
            if (mPresenter.searchKey.isNotBlank()) {

            }
            page = 1
            loadData()
        })
        et_searchs.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                mPresenter.searchKey = s!!.toString()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
        et_searchs.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                IMEUtil.hideIME(mContext, et_searchs)
                mPresenter.searchKey = et_searchs.text.toString().trim()
                page = 1
                mPresenter.getOrderList(page, activity = this)
                true
            }
            false

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK)
            downOnRefresh()
    }

    var refreshing = false

    constructor(parcel: Parcel) : this() {
        page = parcel.readInt()
        tel = parcel.readString()
        type = parcel.readInt()
        refreshing = parcel.readByte() != 0.toByte()
    }

    override fun downOnRefresh() {
        refreshing = true
        page = 1
        loadData()
    }

    override fun showLoading() {
        if (!refreshing)
            super.showLoading()

    }

    override fun onError(mess: String?) {
        super.onError(mess)
        refreshing = false
        onRefreshFinish(false)
        onLoadMoreFinish(false)
    }

    override fun loadMore() {
        refreshing = true
        if (type == 1) {
            onRefreshFinish(true)
            onLoadMoreFinish(true)
            return
        }
        page++
        loadData()
    }

    override fun onDataSuccess(orderList: List<OrderItem>) {
        refreshing = false
        onRefreshFinish(true)
        onLoadMoreFinish(true)
//        if (orderList.isEmpty() && page == 1 || orderAdapter == null && page > 1) {
//            page = 1
//            tv_empty.visibility = View.VISIBLE
//            rv_list.adapter = null
//            return
//        }
//        if (page == 1) {
//            tv_empty.visibility = View.GONE
//            this.list.clear()
//            this.list.addAll(orderList)
//            orderAdapter =
//                OrderAdapter(mContext, list, mPresenter, this, R.layout.item_order_item, type)
//            rv_list.apply {
//                layoutManager = LinearLayoutManager(mContext)
//                adapter = orderAdapter
//            }
//            rv_list.scrollToPosition(0)
//        } else {
//            if (orderList.isEmpty()) {
//                onFinishNoMore()
//            } else {
//                refresh.setEnableLoadMore(true)
//            }
//            var oldCount = orderAdapter!!.itemCount
//            this.list.addAll(orderList)
//            orderAdapter?.notifyItemRangeInserted(
//                oldCount,
//                orderList.size
//            )
//        }
        // 处理空数据场景
        if (orderList.isEmpty()) {
            if (page == 1) {
                // 第一页为空，显示空页面
                tv_empty.visibility = View.VISIBLE
                rv_list.visibility = View.GONE
                orderAdapter?.notifyDataSetChanged()
                Log.d(TAG, "第1页无数据，显示空页面")
            } else {
                // 加载更多时空，提示没有更多数据
                onFinishNoMore()
                Log.d(TAG, "第$page 页无数据，已加载全部")
            }
            return
        }

        // 有数据，隐藏空页面
        tv_empty.visibility = View.GONE
        rv_list.visibility = View.VISIBLE

        // 更新列表数据
        if (page == 1) {
            // 第一页：重置列表
            list.clear()
            list.addAll(orderList)
            // 初始化或更新适配器
            if (orderAdapter == null) {
                orderAdapter = OrderAdapter(mContext, list, mPresenter, this, R.layout.item_order_item, type)
                rv_list.adapter = orderAdapter
                Log.d(TAG, "初始化适配器，加载${list.size}条数据")
            } else {
                orderAdapter?.notifyDataSetChanged()
                Log.d(TAG, "刷新第1页数据，共${list.size}条")
            }
            rv_list.scrollToPosition(0)
        } else {
            // 加载更多：追加数据
            val oldCount = list.size
            list.addAll(orderList)
            orderAdapter?.notifyItemRangeInserted(oldCount, orderList.size)
            Log.d(TAG, "加载更多完成，新增${orderList.size}条，总条数=${list.size}")
        }
    }

    override fun getRefreshTag(): String {
        return super.getRefreshTag() + "_" + type;
    }

    override fun playVoice(path: String) {
        player.play(path)
    }

    /**
     * 接单成功
     */
    override fun receiveSuccess(repairId: String) {
        PageUtils.jumpToResult(this, OrderActivity::class.java, true, "接单成功")
        finish()
    }

    /**
     * 抢单成功
     */
    override fun robSuccess(repairId: String) {
        PageUtils.jumpToResult(this, OrderActivity::class.java, true, "抢单成功")
        finish()
    }


    override fun createPresenter(): MyOrderPresenter {
        return MyOrderPresenter(view = this)
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(page)
        parcel.writeString(tel)
        parcel.writeInt(type)
        parcel.writeByte(if (refreshing) 1 else 0)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<OrderActivity> {
        override fun createFromParcel(parcel: Parcel): OrderActivity {
            return OrderActivity(parcel)
        }

        override fun newArray(size: Int): Array<OrderActivity?> {
            return arrayOfNulls(size)
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        LogUtils.E("OrderActivity 权限结果：requestCode=$requestCode，permissions=${permissions.joinToString()}，grantResults=${grantResults.joinToString()}")

        // 关键：只有定位请求码才转发给LocationManager
        if (requestCode == PermissionUtils.REQUEST_LOCATION) {
            LogUtils.E("转发定位权限结果到LocationManager")
            LocationManager.onRequestPermissionsResult(grantResults, permissions)
        }
    }
}
